package com.audaque.springboot.foshanupload.shardingsphere.config;


import com.audaque.springboot.foshanupload.shardingsphere.utils.ShardingUtil;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;

@Slf4j
public class ShardingTableStrategy implements PreciseShardingAlgorithm<Date> {

    public ShardingTableStrategy() {
    }

    @Override
    public String doSharding(Collection<String> databaseNames, PreciseShardingValue<Date> preciseShardingValue) {
       // 通过分表规则获取目标表
       String tableName = ShardingUtil.getTableName(preciseShardingValue.getLogicTableName(), preciseShardingValue.getValue());
       // 如果存在这个目标表，就返回
       if (databaseNames.contains(tableName)) {
           return tableName;
       }
       // 不存的话，取最近建的表作为目标表
        ArrayList<String> list = new ArrayList<>(databaseNames);
        Collections.sort(list);
        return list.get(list.size() - 1);
    }
}
